<template>
  <div>
    <el-dialog :visible.sync="dialogVisible" width="80%" :before-close="handleClose">
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="简要说明" prop="titleNode">
          <el-input v-model="ruleForm.titleNode"></el-input>
        </el-form-item>
        <el-row>
          <el-col :sm="12">
            <el-form-item label="发布人">
              <el-input v-model="loginname" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="12">
            <el-form-item label="面向对象">
              <el-link type="primary" :underline="false" @click="xuanze">请选择对象</el-link>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :sm="24">
            <el-form-item label="上传附件">
              <el-upload
                class="upload-demo"
                drag
                :action="uploadUrl"
                multiple
                :on-success="handleAvatarSuccess"
                ref="ersty"
                :on-error="handleAvatarError"
                :before-remove="beforeRemove"
                :file-list="fileList"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="正文内容" prop="textNode">
          <quill ref="quill" v-model="ruleForm.text" @textChange="textChange"></quill>
          <!-- <quill ref="quill" :v-model="ruleForm.desc"></quill>  -->
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="dialogValue('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择单位" :visible.sync="dialogVisible2" width="60%" :before-close="handleClose2">
      <el-row>
        <el-col :sm="8">
          <el-select v-model="value1" placeholder="请选择标签类型">
            <el-option v-for="item in options1" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-col>
        <el-col :sm="8">
          <el-select v-model="value2" placeholder="请选择单位级别">
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>

        <el-col :sm="8">
          <el-input v-model="input2" placeholder="搜索单位名称">
            <el-button slot="append" icon="el-icon-search" @click="seeButton"></el-button>
          </el-input>
        </el-col>
      </el-row>
      <el-row style="margin: 10px 0;">
        <el-col
          :sm="12"
          style="text-align:left ;height: 40px; display: flex;align-items: center;font-size: 18px;"
        >
          <div class="g-title">单位数目({{total}}个）</div>
        </el-col>
        <el-col :sm="12" style="text-align:right ;">
          <el-button type="primary" @click="reset">筛选重置</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :sm="24">
          <div class="table-top">
            <el-table
              tooltip-effect="dark"
              ref="multipleTable"
              border
              :data="tableData"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center"></el-table-column>
              <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
              <el-table-column prop="companyName" label="单位名称" show-overflow-tooltip align="center"></el-table-column>
              <!-- <el-table-column prop="titleNode" label="联系地址" width="100" align="center"></el-table-column>
              <el-table-column prop="parentName" label="隶属级别" width="200" align="center"></el-table-column>
              <el-table-column prop="propName" label="单位性质" width="200" align="center"></el-table-column>
              <el-table-column prop="xz" label="单位规格" width="100" align="center"></el-table-column>
              <el-table-column prop="time" label="创建时间" width="100" align="center"></el-table-column>-->
            </el-table>

            <el-row style="padding: 32px 16px;">
              <el-col>
                <el-pagination
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  :page-size="pageSize"
                  :total="total"
                  :current-page="pageNo"
                  @current-change="findCompanys"
                  @size-change="pageSizeChange"
                ></el-pagination>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="selectAll">全部选择</el-button>
        <el-button type="primary" @click="query">确定选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { axios } from "@/api/axios";
import {
  listJson,
  changeIsRead,
  addFileUpload,
  changeArticleById,
  findCompanys,
  findDetails,
} from "@/api/infomaction";
import quill from "@/components/quill/index";
// 引入vuex
import { mapGetters } from "vuex";
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: true,
    },
    data: {
      type: Object,
      default: true,
    },
    addMode: {
      type: Boolean,
    },
  },
  computed: {
    //获取左侧单位勾选的id数组 [1,2,3]
    ...mapGetters(["userInfo", "selectedComIds"]),
  },
  components: {
    quill,
  },
  data() {
    var textNode = (rule, value, callback) => {
      if (this.ruleForm.text == "") {
        return callback(new Error("文本内容分不能为空"));
      } else {
        callback();
      }
    };
    return {
      loginname: "",
      companyId: null, //单位id
      comid: null, //用户id
      comids: "", //单位id多个
      userid: null, //用户id
      companyNmaeId: "",
      uploadUrl: "", //上传地址
      getfile: "", //需要上传的文件
      fileList: [], //存放服务器文件数据
      ruleForm: {
        title: "",
        titleNode: "",
        IssuedBy: "",
        text: "",
        allcom: "",
        comids: null,
        id: "",
        companyId: "",
        companyName: "",
        createtime: "",
        fujianurl: "",
        fjname:""
      },
      listDataSelected: [],
      editData: [],
      dialogVisible2: false,
      options1: [],
      options2: [
        {
          value: 1,
          label: "一级单位",
        },
        {
          value: 2,
          label: "二级单位",
        },
        {
          value: 3,
          label: "三级单位",
        },
      ],

      options3: [
        {
          value: "选项1",
          label: "是",
        },
        {
          value: "选项2",
          label: "否",
        },
      ],
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
      },
      value1: "",
      value2: "",
      value3: "",
      input2: "",
      total: 0,
      total2: 0,
      pageNo: 1,
      tableData: null,
      currentPage: 1, //默认显示第一页
      pageSize: 10, //默认每页显示10条
      totalNum: 1,
      multipleSelection: [],
    };
  },
  watch: {
    data() {
      if (this.addMode == false) {
        if (this.data.length != 0) {
          this.ruleForm = this.data;
          this.fileListUrl();
        }
      }
    },
    dialogVisible() {
      if (this.dialogVisible == true) {
        if (this.addMode) {
          setTimeout(() => {
            this.$refs.ersty.clearFiles();
            this.$refs.quill.setContents("");
            this.ruleForm.text = "";
          }, 0);
        } else {
          setTimeout(() => {
            this.$refs.quill.onHtml(this.ruleForm.textdetails);
          }, 0);
        }
      }
    },
    selectedComIds() {
      this.pageNo = 1;
      this.findCompanys();
    },
  },
  created() {
    this.uploadUrl = this.VUE_APP_BASE_API + "/common/webupload.shtml";
    this.comid = this.userInfo.comid;
    this.userid = this.userInfo.userid;
    this.loginname = this.userInfo.loginname;
    this.findDetails();
    this.findCompanys();
  },
  methods: {
    //删除上传的文件列表
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 修改时把文件名和地址添加到上传组件当中
    fileListUrl() {
      if (this.ruleForm.fjname != "") {
        let url = {
          name: this.ruleForm.fjname,
          url: this.ruleForm.fujianurl,
        };
        this.fileList = [];
        this.fileList.push(url);
        url = []
      }
    },
    //表格多选
    handleSelectionChange(val) {
      this.listDataSelected = val;
    },
    handleClose() {
      this.$emit("update:dialogVisible", false);
    },
    handleClose2() {
      this.dialogVisible2 = false;
    },
    // 全选
    selectAll() {
      this.ruleForm.allcom = 1;
      this.dialogVisible2 = false;
    },
    // 获取文件URL和文件名
    handleAvatarSuccess(res, file, fileList) {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.ruleForm.fujianurl =res.url;
      this.ruleForm.fjname = file.name;
      console.log(this.fujianurl);
    },
    // 成功上传后返回
    handleAvatarError(err, file, fileList) {
      this.$message.error("上传失败");
      console.log(err, file, fileList);
      // alert(err, file, fileList)
    },

    pageSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNo = 1;
      this.findCompanys();
    },
    // 富文本
    textChange(d) {
      this.ruleForm.text = d;
    },
    xuanze() {
      this.dialogVisible2 = true;
    },
    // 下拉框数据
    async findDetails() {
      let data = await findDetails();
      this.options1 = data.tags;
    },
    async findCompanys(pageNo) {
      if (pageNo) {
        this.pageNo = pageNo;
      }
      let params = {
        tagId: this.value1,
        companyName: this.input2,
        companyLev: this.value2,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
      };
      let data = await findCompanys(params);
      console.log(data.total);
      this.tableData = data.data;
      this.total = data.total;
      this.comids = data.comids;
    },
    // 搜索
    async seeButton() {
      let params = {
        tagId: this.value1,
        companyName: this.input2,
        companyLev: this.value2,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
      };
      let data = await findCompanys(params);
      // console.log(params)
      this.tableData = data.data;
      this.total = data.total;
      this.comids = data.comids;
    },
    //添加
    async addFileUpload(comids) {
      if (comids != "") {
        this.companyNameId = comids;
      } else {
        this.companyNameId = null;
      }
      let params = {
        title: this.ruleForm.title,
        simpledetails: this.ruleForm.titleNode,
        // "company.id": this.comid,
        "creator.userid": this.userid,
        textdetails: this.ruleForm.text,
        fujianurl: this.ruleForm.fujianurl,
        fjname: this.ruleForm.fjname,
        allcom: this.ruleForm.allcom,
        comids: this.companyNameId,
      };

      if (this.comid != "") {
        this.$set(params, "company.id", this.comid);
      }
      console.log(params);
      let data = await addFileUpload(params);
      if (data.error == "0") {
        this.$message({
          message: "新增成功",
          type: "success",
        });
        this.empty();
        this.$emit("finish", 1);
        this.$emit("update:dialogVisible", false);
      } else {
        this.$message.error("新增失败，系统错误");
      }
       console.log(this.ruleForm)
    },
    // 修改
    async changeArticleById(comids) {
      if (comids != "") {
        this.companyNameId = comids;
      } else {
        this.companyNameId = "";
      }
      let params = {
        id: this.ruleForm.id,
        title: this.ruleForm.title,
        simpledetails: this.ruleForm.titleNode,
        // "company.id": this.comid,
        uid: this.userid,
        textdetails: this.ruleForm.text,
        fujianurl: this.ruleForm.fujianurl,
        fjname: this.ruleForm.fjname,
        allcom: this.ruleForm.allcom,
        comids: this.companyNameId,
      };
      console.log(this.comid);
      if (this.comid != "") {
        this.$set(params, "company.id", this.comid);
      }
      let data = await changeArticleById(params);
      if (data.error == "0") {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.empty();
        this.$emit("finish", 1);
        this.$emit("update:dialogVisible", false);
      } else {
        this.$message.error("修改失败，系统错误");
      }
      console.log(this.ruleForm)
    },
    //  添加数据
    dialogValue(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.addMode) {
            if (this.ruleForm.allcom === "") {
              // console.log(this.ruleForm.allcom === "");
              // console.log("新增", this.ruleForm.allcom);
              this.$message.error("新增失败，请选择面向对象");
            } else {
              // console.log("新增", this.ruleForm.allcom);

              this.addFileUpload(this.ruleForm.companyId);
            }
          } else {
            console.log("修改", this.ruleForm.allcom);
            if (this.ruleForm.allcom === "") {
              // console.log("修改", this.ruleForm.allcom);
              this.$message.error("修改失败，请选择面向对象");
            } else {
                this.changeArticleById(this.ruleForm.companyId);
            }
          }
        } else {
          this.$message.error("有错误，请检验是否输入必选项");
          return false;
        }
      });
    },
    // 确定全选
    selectAll() {
      if (this.tableData.length == 0) {
        this.$message("请重新搜索，当前没有面向对象数据");
        return;
      }
      console.log(this.tableData);
      if (this.value1 == "" && this.value2 == "" && this.input2 == "") {
        this.$message("没有筛选数据，默认是所有单位选择");
        this.ruleForm.allcom = 1;
        this.ruleForm.companyId = "";
        this.dialogVisible2 = false;
      } else {
        this.ruleForm.companyId = this.comids;
        console.log(this.ruleForm.companyId);
        this.ruleForm.allcom = 0;
        console.log(this.ruleForm.allcom);
        this.dialogVisible2 = false;
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 确定选择
    query() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
         return;
      }
      let num = "";
      this.listDataSelected.forEach((e) => {
        // console.log(e)
        num += e.id + ",";
      });
      num =
        num.substring(num.length - 1) == ","
          ? num.substring(0, num.length - 1)
          : num;
      this.ruleForm.companyId = num;
      console.log(this.ruleForm.companyId);
      this.ruleForm.allcom = 0;
      console.log(this.ruleForm.allcom);
      this.dialogVisible2 = false;
      this.$refs.multipleTable.clearSelection();
    },
    empty() {
      this.ruleForm.id = "";
      this.ruleForm.title = "";
      this.ruleForm.titleNode = "";
      this.ruleForm.fujianurl = "";
      this.ruleForm.fjname = "";
      this.ruleForm.text = "";
      this.ruleForm.allcom = "";
      this.ruleForm.companyId = "";
      this.ruleForm.companyName = "";
      this.fileList = [];
    },
    // 筛选重置
    reset() {
      this.value1 = "";
      this.value2 = "";
      this.input2 = "";
      this.$refs.multipleTable.clearSelection();
    },
  },
};
</script>

<style>
</style>
